/*
**js基础函数H类
**黄总
**2017.6.29
*/
import axios from 'axios'
import qs from 'qs'
axios.defaults.baseURL = 'http://127.0.0.1/learn/php/index.php?s='
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.withCredentials = true

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
import store from '../../store'
import electron from 'electron'

function H () {
	//定义路径
	this.electron = electron
}

H.prototype.ajax = function(url,data,type,fun){
	const that = this
	//let loadingInstance = ElementUI.Loading.service({ fullscreen: true })
	if('get' == type){
		axios.get(url, {
			params: data
		})
		.then(function (response) {
			//loadingInstance.close()
			//在此做统一的验证
			if (response.data.needlogin && !response.data.islogin) {
				//未登录的弹出登陆框
				that.store('showlogin', true)
				// 清空localstorage和store
				that.SL('userinfo')
				that.store('userinfo', {})
				return false
			}
			fun(response.data)
		})
		.catch(function (error) {
			//loadingInstance.close()
			ElementUI.Message.error('网络错误！')
			console.log(error)
		})
	}else if('post' == type){
		axios.post(url, qs.stringify(data))
		.then(function (response) {
			//loadingInstance.close()
			//在此做统一的验证
			if (response.data.needlogin && !response.data.islogin) {
				//未登录的弹出登陆框
				that.store('showlogin', true)
				// 清空localstorage和store
				that.SL('userinfo')
				that.store('userinfo', {})
				return false
			}
			fun(response.data)
		})
		.catch(function (error) {
			//loadingInstance.close()
			ElementUI.Message.error('网络错误！')
			console.log(error)
		})
	}
}
H.prototype.SL = function (obj, ocj) {
	if (ocj) {
		localStorage.setItem(obj, JSON.stringify(ocj))
	} else {
		localStorage.removeItem(obj)
	}
}
H.prototype.GL = function (obj) {
	obj = obj.split('.')
    // 获取数据
    var data = JSON.parse(localStorage.getItem(obj[0]))
    return obj[1] ? data[obj[1]] : data
}
H.prototype.store = function (key,value) {
	store.commit('setstates', [key, value])
}
H.prototype.success = function (info) {
	ElementUI.Message({
		message: info,
		type: 'success'
	})
}
H.prototype.error = function (info) {
	ElementUI.Message.error(info)
}
H.prototype.sendstore = function (key,value) {
	// store.commit('setstates', [key, value])
	this.electron.ipcRenderer.send('H_changestore', [key, value])
}
H.prototype.receivestore = function () {
    this.electron.remote.ipcMain.on('H_changestore', (event, arg) => {
      this.store(arg[0], arg[1])
    })
}
H.prototype.openwin = function (url, winname, refresh, width, height) {
	let that = this
	refresh = refresh ? refresh : false // 是否刷新页面
	const BrowserWindow = this.electron.remote.BrowserWindow
	let w = width ? width : 1000
	let h = height ? height : 660
	const baseurl = process.env.NODE_ENV === 'development'
	  ? 'http://localhost:9080/#'
	  : 'file://'+ __dirname +'\\index.html#'
    let newurl = baseurl + url
	// 查询窗口是否打开
	let winlist = this.GL('winlist') || {}
	if (winlist && winlist[winname]) {
		let win = BrowserWindow.fromId(winlist[winname])
		if (win) {
			let oldurl = win.webContents.getURL()
			if (oldurl != newurl && refresh) {
				// 跳转新地址（暂时后期可以用监听）
				win.webContents.send('H_changeurl', {
					newurl: url,
					winid: winlist[winname]
				})
			}
			win.show()
		} else {
			delete winlist[winname]
			this.SL('winlist', winlist)
			this.openwin(url, winname, refresh, width, height)
		}	
	} else {
		let win = new BrowserWindow({ width: w, height: h, transparent: true, frame: false })
		// win.setResizable(false)
		winlist[winname] = win.id
		this.SL('winlist', winlist)
	    win.on('closed', function () { 
			let ws = that.GL('winlist')
			delete ws[winname]
			that.SL('winlist', ws)
			// that.electron.ipcRenderer.removeAllListeners('H_changestore')
			win = null
		})
		win.on('resize', () => {
	      const [width, height] = win.getContentSize()
	      for (let wc of that.electron.remote.webContents.getAllWebContents()) {
	        // Check if `wc` belongs to a webview in the `win` window.
	        if (wc.hostWebContents &&
	          wc.hostWebContents.id === win.webContents.id) {
	          wc.setSize({
	            normal: {
	              width: width,
	              height: height
	            }
	          })
	        }
	      }
	    })
	    win.loadURL(newurl)
	    win.show()
	}
	
    
}
const HF = new H()
export {HF, ElementUI, store} 
